const Layer = require('./layer');
const methods = require('methods');
function Route() {
    this.stack = [];
    this.methods = {};
}

methods.forEach(method => {
    Route.prototype[method] = function (handles) {
        // 如果是express.Router调用的话，那么handles可能不是数组，因此要将他转为数组
        if (!Array.isArray(handles)) {
            handles = [handles];
        }
        for (let i = 0; i < handles.length; i++) {
            const handle = handles[i];
            const layer = new Layer('', handle);
            // 标识当前处理函数的方法
            layer.method = method;
            // 标记该handle已有的方法,加速匹配
            this.methods[method] = true;
            this.stack.push(layer);
        }
    }
})

Route.prototype.matchMethod = function (requestMethod) {
    return !!this.methods[requestMethod];
}

Route.prototype.dispatch = function (req, res, out) {
    let index = 0;
    const requestMethod = req.method.toLowerCase();
    const next = (err) => {
        if (err) {
            // 如果是错误，抛到外面给use中间件处理错误
            return out(); // 错误处理
        }
        if (index === this.stack.length) return out();
        const layer = this.stack[index++];
        if (this.matchMethod(requestMethod)) {
            layer.handler(req, res, next);
        } else {
            next();
        }
    }

    next();
}

module.exports = Route;